/**
 * 周次计算Hook
 */

'use client';

import { useState, useEffect, useMemo } from 'react';
import { WeekInfo } from '../types/schedule';
import { getCurrentWeek, getDaysUntilSemesterEnd } from '../utils/dateUtils';
import { calculateTotalWeeks } from '../utils/scheduleUtils';
import { Course } from '../types/course';

export interface UseWeekCalculationReturn {
  /** 当前周次 */
  currentWeek: number;
  /** 周信息 */
  weekInfo: WeekInfo;
  /** 设置当前周次 */
  setCurrentWeek: (week: number) => void;
  /** 可选择的周次列表 */
  availableWeeks: number[];
  /** 距离学期结束的天数 */
  daysUntilEnd: number;
}

/**
 * 周次计算Hook
 * @param startDateStr 开学日期字符串
 * @param courses 课程列表
 * @returns 周次相关数据和方法
 */
export const useWeekCalculation = (
  startDateStr: string,
  courses: Course[]
): UseWeekCalculationReturn => {
  const startDate = useMemo(() => new Date(startDateStr), [startDateStr]);
  const totalWeeks = useMemo(() => calculateTotalWeeks(courses), [courses]);
  
  // 计算实际当前周次
  const actualCurrentWeek = useMemo(() => {
    const week = getCurrentWeek(startDate);
    return Math.max(1, Math.min(week, totalWeeks));
  }, [startDate, totalWeeks]);
  
  const [currentWeek, setCurrentWeek] = useState(actualCurrentWeek);
  
  // 当实际周次变化时更新状态
  useEffect(() => {
    setCurrentWeek(actualCurrentWeek);
  }, [actualCurrentWeek]);
  
  // 生成可选择的周次列表
  const availableWeeks = useMemo(() => {
    return Array.from({ length: totalWeeks }, (_, i) => i + 1);
  }, [totalWeeks]);
  
  // 计算学期结束日期
  const endDate = useMemo(() => {
    const end = new Date(startDate);
    end.setDate(end.getDate() + totalWeeks * 7 - 1);
    return end;
  }, [startDate, totalWeeks]);
  
  // 计算距离学期结束的天数
  const daysUntilEnd = useMemo(() => {
    return getDaysUntilSemesterEnd(startDate, totalWeeks);
  }, [startDate, totalWeeks]);
  
  const weekInfo: WeekInfo = useMemo(() => ({
    currentWeek,
    totalWeeks,
    startDate,
    endDate
  }), [currentWeek, totalWeeks, startDate, endDate]);
  
  return {
    currentWeek,
    weekInfo,
    setCurrentWeek,
    availableWeeks,
    daysUntilEnd
  };
};
